package com.cn.crmsystem.service.systemService.impl;

import com.cn.crmsystem.mapper.systemMapper.LoginMapper;
import com.cn.crmsystem.pojo.Login;
import com.cn.crmsystem.pojo.ResultJson;
import com.cn.crmsystem.service.systemService.LoginService;
import com.cn.crmsystem.utils.RedisUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private LoginMapper loginMapper;

    @Override
    public boolean saveToken(String username, String token) {
        return redisUtil.set(username, token, 60 * 30);
    }

    @Override
    public Login getLogin(String username) {
        return loginMapper.getLogin(username);
    }

    @Override
    public ResultJson del() {

        Login login = (Login) SecurityUtils.getSubject().getPrincipal();
        System.out.println(login);
        SecurityUtils.getSubject().logout();//
        redisUtil.del(login.getUserName());
        //if (login == null){
            return new ResultJson().getSuccess("退出成功");
       // }
      //  return new ResultJson().getFail("退出失败");
    }

    @Override
    public ResultJson updatePassword(Login login) {
        if (loginMapper.updatePassword(login) > 0){
            return new ResultJson().getSuccess("修改成功");
        }
        return new ResultJson().getFail("修改失败");
    }

    public ResultJson checkName(String username) {
        username = loginMapper.checkName(username);
        if (username != null && username.trim().length() > 0) {
            return new ResultJson().getSuccess("名字已被注册");
        }
        return new ResultJson().getSuccess("用户可用");
    }

    @Override
    public String checkToken(String name) {
        if (redisUtil.hasKey(name)) {
            //重新 设置为  30分钟;
            redisUtil.expire(name, 30 * 60);
            return (String) redisUtil.get(name);
        }
        return null;
    }


}
